package com.inspection.controller;

import com.inspection.constant.ModelNameEnum;
import com.inspection.dao.FileDao;
import com.inspection.entity.FileDO;
import com.inspection.model.dto.FileQueryDTO;
import com.inspection.service.FileService;
import com.inspection.support.Wrapper;
import com.inspection.support.model.BusinessBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Optional;

@RestController
public class FileController {

    @Autowired
    private FileDao fileDao;

    @Autowired
    private FileService fileService;


    /**
     * 上传考核文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/inspect/lookFile/upload")
    public Wrapper<Long> uploadFile(MultipartFile file, HttpServletRequest request) {
        return Wrapper.ok(fileService.addFile(file, ModelNameEnum.INSPECTION.getValue()));
    }

    /**
     * 上传背景图
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/inspect/lookFile/uploadBackground")
    public Wrapper<Long> uploadBackground(MultipartFile file, HttpServletRequest request) {
        return Wrapper.ok(fileService.addFile(file,ModelNameEnum.BACKGROUND.getValue()));
    }

    /**
     * 上传系统文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/inspect/lookFile/uploadSysFile")
    public Wrapper<Long> uploadSysFile(MultipartFile file, HttpServletRequest request) {
        return Wrapper.ok(fileService.addFile(file,ModelNameEnum.SYSTEM_FILE.getValue()));
    }



    @RequestMapping("/inspect/lookFile/page")
    public Wrapper<Page<FileDO>> pageFile(FileQueryDTO queryDTO) {
        if(queryDTO.getModelName() != null && ModelNameEnum.getByValue(queryDTO.getModelName()) == null){
            throw new BusinessBaseException("400","不存在的文件模块名");
        }
        return Wrapper.ok(fileService.pageFile(queryDTO));
    }


    @RequestMapping("/inspect/lookFile/download")
    public void downloadFile(Long fileId, HttpServletResponse response){
        Optional<FileDO> byId = fileDao.findById(fileId);
        if(!byId.isPresent()){
            throw new BusinessBaseException("400","文件不存在！");
        }
        File f = new File(byId.get().getFilePath());
        if (!f.exists()) {
            throw new BusinessBaseException("400","文件不存在！");
        }
        try {
            BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset(); // 非常重要
//            response.setContentType("application/x-msdownload");
//            response.setContentType("multipart/form-data");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(byId.get().getFileName()+"."+byId.get().getFileType(), "UTF-8") );
            OutputStream out = response.getOutputStream();
            try {
                while ((len = br.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                br.close();
                out.close();
            }
        } catch (Exception e) {
            throw new BusinessBaseException("400","文件下载失败！");
        }
    }


    @RequestMapping("/public/img")
    public void showImg(Long fileId, HttpServletResponse response){
        Optional<FileDO> byId = fileDao.findById(fileId);
        if(!byId.isPresent()){
            throw new BusinessBaseException("400","文件不存在！");
        }
        File f = new File(byId.get().getFilePath());
        if (!f.exists()) {
            throw new BusinessBaseException("400","文件不存在！");
        }
        try (
                InputStream is = new FileInputStream(f);
                OutputStream os = response.getOutputStream();) {
            byte[] buffer = new byte[1024]; // 图片文件流缓存池
            while (is.read(buffer) != -1) {
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }
}
